package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.entity.Message;
import com.example.demo.entity.Student;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class GetStuByIdController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private StudentMapper sm;

    @RequestMapping("/getstubyid")
    public void getstubyid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        if (!NumberUtils.isCreatable(idStr)) {
            response.getWriter().write(JSONObject.toJSONString(Message.failure("format error")));
            return;
        }
       int id = Integer.valueOf(idStr);
        String cache = stringRedisTemplate.opsForValue().get("cache:stu:" + id);
        if(cache!=null&&!"".equals(cache)){
            Student student = JSONObject.parseObject(cache, Student.class);
            response.getWriter().write(JSONObject.toJSONString(Message.success(student)));
        }else {
            if(cache!=null){
                response.getWriter().write(JSONObject.toJSONString(Message.failure("this id is not exit")));
            }
            Student stu = sm.selectStuById(id);
            if (stu != null) {
                response.getWriter().write(JSONObject.toJSONString(Message.success(stu)));
                stringRedisTemplate.opsForValue().set("cache:stu:" + id, JSONObject.toJSONString(stu));
            }else {
                stringRedisTemplate.opsForValue().set("cache:stu:" + id,"",200+ new Random().nextInt(1000), TimeUnit.SECONDS);
                response.getWriter().write(JSONObject.toJSONString(Message.failure("stu is not exist")));
            }
        }
    }

}
